package de.fhwgt.quiz.servlets;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Catalog;
import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import de.fhwgt.quiz.error.QuizError;
import de.fhwgt.quiz.loader.FilesystemLoader;
import de.fhwgt.quiz.loader.LoaderException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;



/**
 * Servlet implementation class WebQuiz
 */
public class CatalogServlet extends HttpServlet {
	private FilesystemLoader CatalogLoader;
	private Map<java.lang.String,Catalog> Catalogs;
	private Set<String> keys;
	private Quiz quiz;
	
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CatalogServlet() {
        super();
		System.out.println("PageInitializer");
		CatalogLoader = new FilesystemLoader("de/fhwgt/quiz/Fragekataloge");
		quiz = Quiz.getInstance();
		quiz.initCatalogLoader(CatalogLoader); 
		try {
			keys = quiz.getCatalogList().keySet();
		} catch (LoaderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    }

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.getParameter("catalogName"));
		try {
			/*for(Player p : quiz.getPlayerList()){
				quiz.changeCatalog(p, "Systemprogrammierung.cat", new QuizError());
			}*/
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			// root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("catalogResponse");
			doc.appendChild(rootElement);												//0 wenn login erfolgreich
			// write the content into xml file
			for(String Catalog : keys) {
				Element catalogEntry = doc.createElement("catalogEntry");
				catalogEntry.appendChild(doc.createTextNode(Catalog));
				catalogEntry.setAttribute("selected", "0");
				try{
					if(quiz.getCurrentCatalog().getName().equals(Catalog)){
						catalogEntry.setAttribute("selected", "1");
					}
				}catch(Exception e){//Spiel noch nicht gestartet(kein Katalog gewählt)}
				}rootElement.appendChild(catalogEntry);
				
			}
			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();					
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(response.getWriter());
			transformer.transform(source, result);
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			StringWriter writer = new StringWriter();
			transformer.transform(new DOMSource(doc), new StreamResult(writer));
			System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));
			
		  } catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		  } catch (TransformerException tfe) {
			tfe.printStackTrace();
		  } catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
